package cn.jobstart.pubInter;



import cn.jobstart.common.*;
import cn.jobstart.common.fileUpload.dto.FilePartUploadDTO;
import cn.jobstart.common.fileUpload.service.FileUploadService;
import cn.jobstart.common.fileUpload.utils.Result;
import cn.jobstart.pubInter.aop.SystemLog;
import cn.jobstart.pubInter.baseVO.UploadFileVO;
import cn.jobstart.pubInter.exception.BusinessException;
import cn.jobstart.pubInter.exception.SkException;
import cn.jobstart.web.common.SkJsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * @author sunke
 * @Date 2019-09-09 16:31:10
 * @description 前台controller基础
 */
@RestController
@Api(tags = "上传文件", description = "上传文件接口")
@Slf4j
public class FrontUploadFileController extends FrontController {




    @Autowired
    private FileUploadService fileUploadService;


    /**
     * 单文件分片上传
     *
     * @param filePart  单次分片的文件
     * @param partIndex 当前分片定位
     * @param partNum   文件分片总数
     * @param fileName  单次分片的文件名称
     */
    @PostMapping("/singleFilePartUpload")
    @ApiOperation(value = "单文件分片上传", notes = "单文件分片上传", httpMethod = "POST")
    @ResponseBody
    public SkJsonResult<FilePartVO> singleFilePartUpload(FilePartUploadDTO dto) {
        int partNum = dto.getPartNum();
        int partIndex = dto.getPartIndex();
        String fileName = dto.getFileName();
        MultipartFile filePart = dto.getFilePart();
        String fileUid = dto.getFileUid();
        log.info("单文件分片上传,总片数:{},分片数:{},文件名:{},大小:{},uid:{}", partNum, partIndex, fileName, filePart.getSize(), fileUid);
        Result<String> result = fileUploadService.singleFilePartUpload(dto, getBaseRoot(), getBaseTempRoot());
        if (HttpStatus.OK.value() != NumberUtil.parseInt(result.getCode())) {
            return SkJsonResult.fail(result.getMsg());
        }

        FilePartVO fileVO = new FilePartVO();

        fileVO.setImg( result.getData());
        fileVO.setWebsite(getFileBaseUrl());
        fileVO.setPartIndex(partIndex);
        fileVO.setPartNum(partNum);
        fileVO.setFileUid(fileUid);
        fileVO.setFinish(NumberUtil.parseInt(result.getMsg()));
        return SkJsonResult.ok().setData(fileVO);
    }

    /**
     * 多文件分片上传
     *
     * @param filePart  单次分片的文件
     * @param partIndex 当前分片定位
     * @param partNum   文件分片总数
     * @param fileName  单次分片的文件名称
     */
    @PostMapping("/multipleFilePartUpload")
    @ApiOperation(value = "多文件分片上传", notes = "多文件分片上传", httpMethod = "POST")
    @ResponseBody
    public SkJsonResult<List<FilePartVO>> multipleFilePartUpload(FilePartUploadDTO dto) {

        int partNum = dto.getPartNum();
        int partIndex = dto.getPartIndex();
        String fileName = dto.getFileName();
        MultipartFile filePart = dto.getFilePart();
        String fileUid = dto.getFileUid();

        log.info("多文件分片上传,总片数:{},分片数:{},文件名:{},大小:{},uid:{}", partNum, partIndex, fileName, filePart.getSize(), fileUid);
        Result<String> result = fileUploadService.multipleFilePartUpload(dto, getBaseRoot(), getBaseTempRoot());

        if (HttpStatus.OK.value() != NumberUtil.parseInt(result.getCode())) {
            return SkJsonResult.fail(result.getMsg());
        }


        FilePartVO fileVO = new FilePartVO();

        fileVO.setImg( result.getData());
        fileVO.setWebsite(getFileBaseUrl());
        fileVO.setPartIndex(partIndex);
        fileVO.setPartNum(partNum);
        fileVO.setFileUid(fileUid);
        fileVO.setFinish(NumberUtil.parseInt(result.getMsg()));
        return SkJsonResult.ok().setData(fileVO);


    }



    @ApiOperation(value = "下载文件从Code", notes = "下载附件从Code", httpMethod = "GET")
    @GetMapping("downloadFileByCode/{code}/{fileName}")
    @SystemLog(title = "下载文件从Code", method = "downloadFileByCode", businessType = 6)
    public void downloadFileByCode(@PathVariable String code, @PathVariable(required = false,value = "") String fileName, HttpServletResponse response) throws Exception {
        String filePath = StringUtil.toString(getRedisUtil().get(code));
        if (StringUtil.isNullOrEmpty(filePath)) {
            return;
        }
        //10分钟有效
        getRedisUtil().del(code);
        String fullFilePath = getBaseRoot() + File.separator + filePath;

        String suffix = StringUtil.getFileNameAndSuffix(filePath)[1];
        if(StringUtil.isNullOrEmpty(fileName)){
            fileName= GetCode.createOrderNo(20);
        }

        String fileNameStr = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");


        response.setContentType("application/x-download");

        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileNameStr + "." + suffix + "\"");


        FileUtil.writeFileToOutputStream(fullFilePath, response.getOutputStream());


    }


    @ApiOperation(value = "生成下载文件Code", notes = "生成下载文件Code", httpMethod = "POST")
    @PostMapping("createFileCode")
    @SystemLog(title = "生成下载文件Code", method = "createFileCode", businessType = 0)
    public SkJsonResult<String> createFileCode(@RequestBody FileDTO dto, HttpServletRequest request, HttpServletResponse response) throws Exception {


        String code = GetCode.createRandom(10);
        //10分钟有效
        getRedisUtil().set(code, dto.getImg(), 600);


        return SkJsonResult.ok().setData(code);


    }



    /**
     * 上传文件
     *
     * @param file
     * @param type
     * @return
     * @throws SkException
     */
    @ApiOperation(value = "上传图片通过Code", notes = "上传图片通过Code", httpMethod = "POST")
    @PostMapping("/uploadFileFromCode")
    @ResponseBody
    public SkJsonResult<UploadFileVO> uploadFileFromCode(
            @RequestParam("file") MultipartFile file,
            @RequestParam("code") String code
            , @ApiParam("文件目录") @RequestParam(value = "type", defaultValue = "evaluation", required = false) String type
            ,@ApiParam("压缩比例0-1") @RequestParam(value = "scale", defaultValue = "1", required = false) float scale
            ,@ApiParam("压缩质量0-1") @RequestParam(value = "outputQuaFlitySize", defaultValue = "1", required = false) float outputQualitySize


    ) throws SkException {



        if(StringUtil.isNullOrEmpty(code)){
            throw new BusinessException("用户未登录@@33061");
        }
        String value= StringUtil.toString(getRedisUtil().get(code));
        if(StringUtil.isNullOrEmpty(value)){
            throw new BusinessException("用户未登录@@33061");
        }


        UploadFileVO vo = new UploadFileVO();
        vo.setWebsite(getFileBaseUrl());
        vo.setImg(getUploadFile(file, type, null,scale,outputQualitySize));

        return SkJsonResult.ok().setData(vo);
    }


    /**
     * 上传文件
     *
     * @param file
     * @param type
     * @return
     * @throws SkException
     */
    @ApiOperation(value = "上传图片", notes = "上传图片接口", httpMethod = "POST")
    @PostMapping("/uploadFile")
    @ResponseBody
    public SkJsonResult<UploadFileVO> uploadFile(
            @RequestParam("file") MultipartFile file
            , @ApiParam("文件目录") @RequestParam(value = "type", defaultValue = "evaluation", required = false) String type
            ,@ApiParam("压缩比例0-1") @RequestParam(value = "scale", defaultValue = "1", required = false) float scale
            ,@ApiParam("压缩质量0-1") @RequestParam(value = "outputQualitySize", defaultValue = "1", required = false) float outputQualitySize


    ) throws SkException {

        UploadFileVO vo = new UploadFileVO();
        vo.setWebsite(getFileBaseUrl());
        vo.setImg(getUploadFile(file, type, null,scale,outputQualitySize));

        return SkJsonResult.ok().setData(vo);
    }





    /**
     * html to png
     *
     * @return
     * @throws SkException
     */
    @ApiOperation(value = "html生成png图片", notes = "html生成png图片", httpMethod = "POST")
    @PostMapping("/html2Img")
    @ResponseBody
    public SkJsonResult<UploadFileVO> html2Img(@RequestBody HtmlToImgDTO dto) throws SkException {

        UploadFileVO vo = new UploadFileVO();
        vo.setWebsite(getFileBaseUrl());

        String fieDir = Const.UPLOAD_PATH + "/bar";
        String filePath = YXDate.getFormatDate2String(new Date(), "yyyyMMddHHmmss") + ".png";


        HtmlToImageUtil.html2Img(dto.getWidth(),dto.getHeight(),dto.getContent(), fieDir, filePath);

        vo.setImg("bar/"+filePath);

        return SkJsonResult.ok().setData(vo);
    }


}